<?php

namespace app\common\model\company;

use app\api\controller\Pub;
use app\common\model\power\Rolepower;
use app\common\model\user\User;
use app\common\model\customer\Subscribe;
use think\Model;

class CompanyTouch extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'companytouch';
    protected $pk    = 'Id';

    public function companyinfo()
    {
        return $this->hasOne('app\common\model\company\Company', 'CompanyId', 'CompanyId');
    }

    public function bussinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'BussinessId');
    }

    /**
     * 创建企业摸排信息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_create($idata)
    {
        if (empty($idata['CompanyId'])) {
            return moerr('缺少企业id');
        }
        $sb = Company::get($idata['CompanyId']);
        if (empty($sb)) {
            return moerr('缺少企业信息');
        }
        $Customer               = new CompanyTouch();
        $Customer->CreateTime   = date('Y-m-d H:i:s', time());
        $Customer->CreateUserId = Pub::userid();
        $filed                  = ['CompanyId', 'UserName', 'UserTel', 'TouchTime', 'ZhuYaoQingKuang', 'WuRanXSQK', 'WuRanZGYJ', 'WuRanBZ', 'TaiZhangZhuCunXSQK', 'TaiZhangZhuCunZGYJ', 'TaiZhangZhuCunBZ', 'BiaoShiXSQK', 'BiaoShiZGYJ', 'BiaoShiBZ', 'WeiFeiXSQK', 'WeiFeiZGYJ', 'WeiFeiBZ', 'TaiZhangXSQK', 'TaiZhangZGYJ', 'TaiZhangBZ', 'ZhuCunXSQK', 'ZhuCunZGYJ', 'ZhuCunBZ', 'Note', 'Img', 'TouchUserName', 'TouchUserTel', 'WuRanImg', 'TaiZhangZhuCunImg', 'BiaoShiImg', 'WeiFeiImg', 'TaiZhangImg', 'ZhuCunImg'];
        foreach ($filed as $key => $value) {
            if (!empty($idata[$value])) {
                $Customer->$value = $idata[$value];
            }
        }
        $Customer->save();
        if (!empty($idata['list'])) {
            foreach ($idata['list'] as $key => $value) {
                $idata['list'][$key]['CompanyTouchId'] = $Customer->Id;
            }
            $ctg = new CompanyTouchGood;
            $ctg->saveAll($idata['list']);
        }
        return $Customer->Id;
    }

    /**
     * 创建企业摸排信息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_re($idata)
    {
        if (empty($idata['ToucheId'])) {
            return moerr('缺少排查清单id');
        }
        $Customer = CompanyTouch::get($idata['ToucheId']);
        if (empty($Customer)) {
            return moerr('没找到排查清单信息');
        }
        //权限验证
        $company = Company::get($Customer['CompanyId']);
        if ($Customer['CreateUserId'] == Pub::userid()) {
            //创建排查清单 通过验证
        } else if (Rolepower::ispower(204007)) {
            //管理员权限
        } else if ($company->BussinessId == Pub::userid()) {
            //客户负责人 通过验证
        } else {
            return moerr('权限不足，无法修改排查信息');
        }

        $Customer->CreateUserId = Pub::userid();
        $filed                  = [ 'UserName', 'UserTel', 'TouchTime', 'ZhuYaoQingKuang', 'WuRanXSQK', 'WuRanZGYJ', 'WuRanBZ', 'TaiZhangZhuCunXSQK', 'TaiZhangZhuCunZGYJ', 'TaiZhangZhuCunBZ', 'BiaoShiXSQK', 'BiaoShiZGYJ', 'BiaoShiBZ', 'WeiFeiXSQK', 'WeiFeiZGYJ', 'WeiFeiBZ', 'TaiZhangXSQK', 'TaiZhangZGYJ', 'TaiZhangBZ', 'ZhuCunXSQK', 'ZhuCunZGYJ', 'ZhuCunBZ', 'Note', 'Img', 'TouchUserName', 'TouchUserTel', 'WuRanImg', 'TaiZhangZhuCunImg', 'BiaoShiImg', 'WeiFeiImg', 'TaiZhangImg', 'ZhuCunImg'];
        foreach ($filed as $key => $value) {
            if (isset($idata[$value])) {
                $Customer->$value = $idata[$value];
            }
        }
        $Customer->save();
        //删除之前的排查信息
        CompanyTouchGood::where('CompanyTouchId',$Customer->Id)->delete();
        //将最新的增加进去
        if (!empty($idata['list'])) {
            foreach ($idata['list'] as $key => $value) {
                $idata['list'][$key]['CompanyTouchId'] = $Customer->Id;
            }
            $ctg = new CompanyTouchGood;
            $ctg->saveAll($idata['list']);
        }
        return $Customer->Id;
    }
    
    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function user_getinfo($id, $hidden = ['OperationLog'])
    {
        $data = CompanyTouch::get($id);
        if (empty($data)) {
            return moerr('没有找到您需要的信息');
        }
        $data['power_reinfo'] = false;//修改摸排表权限
        //权限验证
        $company = Company::get($data['CompanyId']);
        if ($data['CreateUserId'] == Pub::userid()) {
            //创建排查清单 通过验证
            $data['power_reinfo'] = true;
        } else if (Rolepower::ispower(204007)) {
            //管理员权限
            $data['power_reinfo'] = true;
        } else if ($company->BussinessId == Pub::userid()) {
            //客户负责人 通过验证
            $data['power_reinfo'] = true;
        } else {
            //判断是否为客户
            $mycompany = Company::where('UserId',Pub::userid())->find();
            if(!empty($mycompany) && $company['CompanyId']==$mycompany['CompanyId']){
                //企业负责人通过验证
            }else{
                return moerr('权限不足，无法查看此客户排查信息');
            }
        }
        $data['readyAcountList'] = CompanyTouchGood::user_getlist($id);
        $data['CompanyName']     = $company->Name;
        $data['Subscribe'] = Subscribe::where('CompanyTouchId',$id)->find();
        return $data;
    }

    /**
     * 删除此摸排单
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function deleteinfo($id)
    {
        $data = CompanyTouch::get($id);
        if (empty($data)) {
            return moerr('没有找到您需要的信息');
        }
        //权限验证
        if ($data['CreateUserId'] == Pub::userid()) {
            //创建排查清单 通过验证
        } else if (Rolepower::ispower(204007)) {
            //管理员权限
        } else {
            return moerr('权限不足，仅业务负责人及创建人可删除摸排信息');
        }
        $data->delete();
        return true;
    }

/**
 * 获取订单列表
 * @param  [type] $data    [主数据]
 * @param  string $type    [查询类型/hawa/buss]
 * @param  [type] $is_page [是否分页显示]
 * @return [type]          [description]
 */
    public static function usergetlist($data, $type = 'buss', $is_page = true)
    {
        $rdata = new CompanyTouch;
        if ($type == 'buss') {
            $visible = ['Id', 'TouchTime', 'CompanyId', 'UserName', 'TouchUserName','companyinfo'=>['Name']];
        }else if ($type == 'mana') {
            $visible = ['Id', 'TouchTime', 'CompanyId', 'UserName', 'TouchUserName','companyinfo'=>['Name']];
        }else {
            return moerr('缺少参数');
        }
        if (!empty($data['field'])) {
            $visible = array_merge($data['field'], $visible);
        }

        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];

        if (!empty($data['field'])) {
            $rdata = $rdata->field($visible);
        }
        if (!empty($visible)) {
            $rdata = $rdata->visible($visible);
        }

        if (!$is_page) {
            $rdata = $rdata->limit(10);
        }
        $rdata = $rdata->with('companyinfo');
        $rdata = $rdata->select();

        $ndata['list'] = $rdata->toArray();

        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }

    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param  boolean $wtnote [是否记录]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = Customer::get($data['id']);
        $userinfo = User::getinfo();
        if ($info->guard_state && $info->BussinessId !== Pub::userid() && !Rolepower::ispower(204007)) {
            return moerr('该客户处于保护期,无法修改', '', 'goback');
        }

        $reinfo  = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo  = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            if ($key == 'OtherTel') {
                if (is_array($info->$key)) {
                    $ovalue = implode(',', $info->$key);
                } else {
                    $ovalue = $info->$key;
                }
            } else {
                $ovalue = $info->$key;
            }

            if ($key == 'State' && $value !== $ovalue) {
                if ((int) $ovalue !== (int) $value) {
                    $info->$key = $value;
                    //value将改变成文字所以提前赋值
                    $value   = $info->getStatusText((int) $value);
                    $ovalue  = $info->getStatusText((int) $ovalue);
                    $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                }
            } else if ($key == 'isPlanform') {
                if ($value !== $ovalue && (int) $ovalue !== (int) $value) {
                    $info->$key = $value;
                    $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                }
            } else if ($key == 'BussinessId' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $value . User::get($value)->Name;
                $ovalue  = $ovalue . User::get($ovalue)->Name;
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if ($key == 'CompanyId' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $value . Company::get($value)->Name;
                $ovalue  = $ovalue . Company::get($ovalue)->Name;
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if (!empty($value) && $ovalue !== $value) {
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            return moerr('没有找到需要调整的数据');
        }
    }

    public static function getfiledname($str)
    {
        $filename = [
            'State'           => '状态',
            'CompanyId'       => '企业id',
            'Name'            => '企业名称',
            'Address'         => '企业地址',
            'Lon'             => '经度',
            'Lat'             => '纬度',
            'Tel'             => '联系电话',
            'OtherTel'        => '其他电话',
            'LicenseNumber'   => '信用代码',
            'UserName'        => '负责人姓名',
            'UserTel'         => '负责人电话',
            'Type'            => '企业分类',
            'Scale'           => '产废规模',
            'Note'            => '备注',
            'Img'             => '图片备注',
            'AppointmentTime' => '预约时间',
            'Visitingtime'    => '上门时间',
            'BindTime'        => '绑定时间',
            'BussinessId'     => '业务id',
            'isPlanform'      => '是否接入平台',
        ];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

}
